
import { deleteImg } from '@/api/doc';
import store from '@/store/index.js';
import { doGet, doSave, doDelete } from "@/utils/offline/sqlite/index.js";
import { uploadImageFromBase64,localPathToBase64, uploadVideo, } from '@/utils/imageOperation.js'
import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
// #ifdef APP-PLUS
import { DB } from "@/utils/offline/sqlite/dbinit.js";
// #endif

export default async function() {
	try {
		// const DB = store.getters.getDB
		DB.initDatabase()
		// uni.showLoading({
		// 	title: '加载中',
		// 	mask:true
		// });
		
		//获取服务端最新的所有病害数据
		const resq = JSON.parse(uni.getStorageSync('lineData'))
		let res =  await XUNJIAN.getDetailsList(resq)
		console.log(res,'当前区间站点所有的病害数据');
		
		//查询离线操作的历史数据
		console.warn(await DB.select(`select id,startNumber, endNumber, version, code, submit from diseases`));
		let hisDiseases = await DB.select(`select * from diseases where id>0 and version>0 and code !='' and submit=0`)
		console.log(hisDiseases,'历史数据数据库查询1');
		hisDiseases =  hisDiseases.filter(d => !res.result.some(h => h.code === d.code))
		console.log(hisDiseases,'历史数据数据库查询2');
		// return
		
		
		let taskSubmitHisDiseases = hisDiseases.map(item => submitHistoryDisease(item))
		await Promise.all(taskSubmitHisDiseases)
		
		
		//查询离线新增数据
		
		let newDiseases = await DB.select(`select * from diseases where id < 0 and code !='' and submit=0`)
		newDiseases =  newDiseases.filter(d => !res.result.some(h => h.code === d.code))
		console.log(newDiseases,'新增数据数据库查询');
		let taskSubmitNewDiseases = newDiseases.map(item => submitNewDisease(item))
		// await Promise.all(taskSubmitNewDiseases)
		await Promise.all(taskSubmitNewDiseases)
		
		
		// //删除需要删除的离线图片数据到服务器
		let idsByimg = await DB.select(`select id from deletedImages where id > 0`)
		let taskDeleteImages = idsByimg.map(item => submitDelete(item.id))
		await Promise.all(taskDeleteImages)
		// uni.hideLoading();
		return true
	} catch (e) {
		console.error('submitOfflineData error', e, 165);
		return false
	}
}
/**
 * @param {Object} disease
 * 提交新增病害及其图片信息
 */
async function submitNewDisease(disease) {
	console.log(disease, '新增');
	try {
		// 提交前本地库中的图片docId和视频docId
		const _docId = disease.docId
		const _videoDocId = disease.videoDocId
		
		//如果有图片
		if (disease.docId) {
			// const DB = store.getters.getDB
			let imgs = await DB.select(`select * from images where docInfoId = ${disease.docId} `)
			if (imgs.length > 0){
				let base64List = []
				for(let it of imgs) {
					base64List.push((await localPathToBase64(it.url)).split(",")[1])
				}
				console.warn(base64List.length,'图片数据测试长度');
				let {
					result: {
						id: docId
					}
				} = await uploadImageFromBase64({
					dataList: JSON.parse(imgs[0].dataList),
					base64List
				})
				disease.docId = docId
			}
			
		}
		//如果有视频
		if (disease.videoDocId) {
			let videos = await DB.select(`select * from images where docInfoId = ${disease.videoDocId}`)
			console.log(videos,'视频');
			if (videos.length > 0) {
				let videosList = []
				for(let it of videos) {
					//如果是拍摄上传需要自己拼接路径
					if(it.url.startsWith("_doc")){
						it.url = 'file://' +  plus.io.convertLocalFileSystemURL(it.url);
					}
					videosList.push(it.url)
				}
				
				// 上传第一个视频,拿到docId
				let result = await uploadVideo({videosList:videosList.slice(0,1)})
				// 使用第一个视频文件的docId,将后续剩余视频文件补充到这个docId的附件清单中
				if(result.result.id) {
					const $docId = result.result.id        //首个视频文件获取到的docId
					const restVideos = videosList.slice(1) //剩余视频
					await Promise.all(restVideos.map(v=>uploadVideo({docId:$docId, videosList: [v]})))
				} 
				disease.videoDocId = result.result.id
				console.log(disease.videoDocId,'--------');
			}
			
		}
		
		try {			
			//标记本地状态为正在提交
			await DB.execute(`update diseases set submit=1 where id=${disease.id}`)
			console.log(disease,'入参');
			let result = await XUNJIAN.diseaseOrderSave({...disease, id: null})
			if(!result.success) {
				throw new Error(result.message)
			}
			//服务端返回结果后更新状态到本地库
			const {id: $id, code: $code} = result.result
			await DB.execute(`update diseases set id=${$id}, code=${$code} where id = ${disease.id}`)
			//更新本地库的图片docId
			if(disease.docId && disease.docId>0) {
				await DB.execute(`update diseases set docId     = ${disease.docId} where id = ${$id}`)
				await DB.execute(`update images   set docInfoId = ${disease.docId} where docInfoId = ${_docId}`)
			}
			//更新本地库的视频docId
			if(disease.videoDocId && disease.videoDocId>0) {
				await DB.execute(`update diseases set videoDocId = ${disease.videoDocId} where id = ${$id}`)
				await DB.execute(`update images   set docInfoId  = ${disease.videoDocId} where docInfoId = ${_videoDocId}`)
			}
			console.log(`提交新增病害[id=${disease.id}]结果`, result)			
		} catch (err) {
			console.error(`提交新增病害[id=${disease.id}]失败:`, err)
		} finally {
			//标记本地状态为已提交
			await DB.execute(`update diseases set submit = 0 where id = ${disease.id}`)
			console.warn(`提交新增病害[id=${disease.id}]结束，更新本地库中的submit状态`)
		}
		

	} catch (e) {
		console.error('submitNewDisease erroe utils', e);
	}
}
/**提交历史病害变更信息及其图片信息*/
async function submitHistoryDisease(disease) {
	console.warn(disease, 'utils--121');
	try {
		//图片相关逻辑
		if (disease.docId) {
			// const DB = store.getters.getDB
			let imgs = await DB.select(`select * from images where docInfoId = ${disease.docId} and id < 0`)
			console.log(imgs, '126---utils');
			if (imgs.length >  0) {
				let base64List = []
				for(let it of imgs) {
					base64List.push((await localPathToBase64(it.url)).split(",")[1])
				}
				let formData = {
					dataList: JSON.parse(imgs[0].dataList),
					base64List
				}
				if(disease.docId > 0) {
					formData.docId = disease.docId
				}
				let {result: {id: docId}} = await uploadImageFromBase64(formData)
				if (disease.docId < 0) {
					disease.docId = docId
				}
			}
			
		}
		//视频相关逻辑
		if (disease.videoDocId) {
			// const DB = store.getters.getDB
			let videos = await DB.select(`select * from images where docInfoId = ${disease.videoDocId} and id < 0`)
			console.log(videos, '164---utils');
			if (videos.length > 0) {
				let videosList = []
				for(let it of videos) {
					//如果是拍摄上传需要自己拼接路径
					if(it.url.startsWith("_doc")){
						it.url = 'file://' +  plus.io.convertLocalFileSystemURL(it.url);
					} 
					videosList.push(it.url)
				}
				let formData = {
					docId:undefined
				}
				if(disease.videoDocId > 0) {
					formData.docId = disease.videoDocId
				}
				
				let result = await uploadVideo({docId:formData.docId,videosList})
				console.log(result,'179行');
				if (disease.videoDocId < 0) {
					disease.videoDocId = result.result.id
				}
			}
			
		}
		
		try {
			await DB.execute(`update diseases set submit = 1 where id = ${disease.id}`)
			console.log(disease,'历史未修复入参');
			let result = await XUNJIAN.diseaseOrderSave({...disease})
			console.log(`提交历史病害[id=${disease.id}]结果`, result)
		} catch (err) {
			console.error(`提交历史病害[id=${disease.id}]失败:`, err)
		} finally {
			await DB.execute(`update diseases set submit = 0 where id = ${disease.id}`)
			console.warn(`提交历史病害[id=${disease.id}]结束，更新本地库中的submit状态`)
		}
	} catch (e) {
		console.error('submitHistoryDisease error:', e);
	}
}

/**
 * @param {Object} id
 * 提交离线期间删除的图片信息
 */
async function submitDelete(id) {
	try {
		await deleteImg({
			id
		})
		console.log('提交删除图片数据到服务器返回的结果--utils', result);

	} catch (e) {
		console.error('taskDelete erroe utils', e);
	}
}


/**清除本地数据库缓存数据 */
export async function clearLoaclDBTable() {
	await DB.clearTable(`diseases`)
	await DB.clearTable(`diseaseOrderLog`)
	// await DB.clearTable(`diseaseGrade`)
	// await DB.clearTable(`diseaseContent`)
	// await DB.clearTable(`keywordsTable`)
	// await DB.clearTable(`diseaseStatus`)
	// await DB.clearTable(`repairTable`)
	// await DB.clearTable(`stations`)
	await DB.clearTable(`images`)
	await DB.clearTable(`deletedImages`)
	await DB.clearTable(`lastFillingRecord`)
	// await DB.close()
}